package com.jigar;



import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;



public class EmployeeSearch {
	private static SessionFactory factory;
	
	public Integer addEmployee(String fname, String lname){
		factory = new Configuration().configure().buildSessionFactory();
		Session session = factory.openSession();//created session from db
		Transaction tx = null;
		Integer employeeID = null;
		try{
			tx = session.beginTransaction();//starts transaction
			SimpleData employee = new SimpleData(fname, lname);//created object which hibernate understands
			employeeID = (Integer) session.save(employee);//returns pk
			tx.commit();
		}catch (HibernateException e) {
			if (tx!=null) tx.rollback();//if transaction created and something happened
			e.printStackTrace(); 
		}finally {
			session.close(); 
		}
		return employeeID;
	}
	
	public void updateEmployee(Integer EmployeeID, String lASTNAME ){
		factory = new Configuration().configure().buildSessionFactory();
	      Session session = factory.openSession();
	      Transaction tx = null;
	      try{
	         tx = session.beginTransaction();
	         SimpleData employee = 
	                    (SimpleData)session.get(SimpleData.class, EmployeeID); 
	         employee.setLASTNAME(lASTNAME);
			 session.update(employee); 
	         tx.commit();
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	   }
	
	 public List listEmployees( ){
		 factory = new Configuration().configure().buildSessionFactory();
	      Session session = factory.openSession();
	      List employees =null;
	      System.out.println("list SimpleData");
	      Transaction tx = null;
	      try{
	         tx = session.beginTransaction();
	         employees = session.createQuery(" from SimpleData").list(); 
	         Iterator iterator = employees.iterator();
	         while( iterator.hasNext()){
	        	SimpleData employee = (SimpleData) iterator.next(); 
	            System.out.println("  Employee: " + employee); 
	         }
	         tx.commit();
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
		return employees;
	   }
}
